import { InputService } from './currency.service';
import { CurrencyPipe } from '@angular/common';

export class InputHandler {
  private inputService: InputService;
  private onModelChange: Function;
  private onModelTouched: Function;
  private htmlInputElement: HTMLInputElement;

  //
  constructor(currencyPipe: CurrencyPipe, htmlInputElement: HTMLInputElement, options: any) {
    this.inputService = new InputService(currencyPipe, htmlInputElement, options);
    this.htmlInputElement = htmlInputElement;
  }

  private isReadOnly() {
    return this.htmlInputElement && this.htmlInputElement.readOnly;
  }

  updateOptions(options: any): void {
    this.inputService.updateOptions(options);
  }

  handleCompositionEnd(e: any) {
    if (this.isReadOnly()) {
      return;
    }
    e.preventDefault();
    this.inputService.addNumber(true, e.target.value);
    this.onModelChange(this.inputService.value);
  }

  handleCompositionBlur(e: any) {
    if (this.isReadOnly()) {
      return;
    }
    e.preventDefault();
    this.inputService.addNumber(false, e.target.value);
    this.onModelChange(this.inputService.value);
  }

  handleKeypress(e: any): void {
    if (this.isReadOnly()) {
      return;
    }
    const key = e.key;
    const aKeysFilter = ['Backspace', 'Delete', '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
    const isInclude = aKeysFilter.filter((_key) => {
      return _key === key;
    });

    if (!isInclude.length) {
      e.preventDefault();
      return;
    }
  }

  handleFocus(e: any): void {
    if (this.isReadOnly()) {
      return;
    }
    this.inputService.formatNumber(e.target.value);
  }

  // ====
  getOnModelChange(): Function {
    return this.onModelChange;
  }

  setOnModelChange(callbackFunction: Function): void {
    this.onModelChange = callbackFunction;
  }

  getOnModelTouched(): Function {
    return this.onModelTouched;
  }

  setOnModelTouched(callbackFunction: Function) {
    this.onModelTouched = callbackFunction;
  }

  setValue(value: any): void {
    this.inputService.value = value;
  }
}
